Cousins in a Binary Tree
Medium
Question
Given the root of a binary tree and two of its nodes' values, return whether the nodes are cousins of each other.
Nodes are cousins if they have the same depth and different parents.
The values of the nodes in the tree are all unique.
Input: root = [1, 2, 3, 4, 5, None, 7], a = 4, b = 7
Output: True
4 and 7 are cousins because they're at the same depth and have different parents.
Input: root = [1, 2, 3, None, 5], a = 2, b = 3
Output: False
2 and 3 are not cousins because they have the same parents.
Input: root = [1, 2, 3, 4], a = 3, b = 4
Output: False
3 and 4 are not cousins because they have different depths.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Which of these pairs of nodes is cousins for the following tree? [1, 2, 3, 4, None, None, 7]
a = 4, b = 7
a = 2, b = 7
a = 2, b = 3
a = 3, b = 4
Take a moment to understand the problem and think of your approach before you start coding.